﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Milan;
using Milan.IO;

public partial class upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
		string response = "err:1:Unknown Error";
		if (!IsPostBack)
		{
			string op = Request["op"];
			if (op != null)
			{
				Milan.Deploy.OpCodes opCodes = (Milan.Deploy.OpCodes)Enum.Parse(typeof(Milan.Deploy.OpCodes),op,false);
				if (Request["product"] != null && Request["version"]!=null)
					m_server = new Milan.Deploy.Server(Request["product"], Version.Parse(Request["version"]));
				switch (opCodes)
				{
					case Milan.Deploy.OpCodes.upload:
						UploadFile(ref response);
						break;
					case Milan.Deploy.OpCodes.setreleasetype:
						SetReleaseType(ref response);
						break;
					case Milan.Deploy.OpCodes.log:
						UploadLogFile(ref response);
						break;
					case Milan.Deploy.OpCodes.email:

					case Milan.Deploy.OpCodes.err:
						UploadLogFile(ref response,true);
						break;
					case Milan.Deploy.OpCodes.ver:
						response = "ok:0:1";
						break;
					case Milan.Deploy.OpCodes.install:
						RegisterInstaller(ref response);
						break;
				}
			}
		}
		Response.Write(response);
    }
	private void UploadFile( ref string response)
	{
		var uploadedFiles = Request.Files;
		for (int i = 0; i < uploadedFiles.Count; i++)
		{
			HttpPostedFile userPostedFile = uploadedFiles[i];

			try
			{
				if (userPostedFile.ContentLength > 0)
				{
					string destination = Request["dest"];
					//string token = Request["token"];
					string path = Path.Combine(Server.MapPath("products"), m_server.ProductPath, m_server.VersionPath);
					Directory.CreateDirectory(path);
					userPostedFile.SaveAs(Path.Combine(path,destination));
					response = "ok:0:success";
				}
			}
			catch (Exception)
			{
			}
		}
	}
	/// <summary>
	/// Uploads a file to the log directory.
	/// </summary>
	/// <param name="response"></param>
	/// <param name="reportNow">If true, then this file is sent right now.</param>
	private void UploadLogFile(ref string response, bool reportNow = false)
	{
		var uploadedFiles = Request.Files;
		for (int i = 0; i < uploadedFiles.Count; i++)
		{
			HttpPostedFile userPostedFile = uploadedFiles[i];

			try
			{
				if (userPostedFile.ContentLength > 0)
				{
					string destination = Request["dest"];
					//string token = Request["token"];
					string path = Path.Combine(Server.MapPath("products"), m_server.ProductPath, "logs");
					Directory.CreateDirectory(path);
					userPostedFile.SaveAs(Path.Combine(path, destination));
					response = "ok:0:success";
					var productName = Request.Params["product"].Replace(' ','_');
					if( reportNow)
						log.SendLog(productName,Request["machineid"]);
				}
			}
			catch (Exception)
			{
			}
		}
	}
	private void SetReleaseType( ref string response)
	{
		var releaseType = (Milan.Deploy.ReleaseType)Enum.Parse(typeof(Milan.Deploy.ReleaseType), Request["type"]);
		string releaseFile = Path.Combine(Server.MapPath("products"), m_server.ProductPath,releaseType.ToString().ToLower()+".txt");
		File.WriteAllText(releaseFile, m_server.CurrentVersion.ToString());
	}
	private Milan.Deploy.Server m_server;
	/// <summary>
	/// The install
	/// </summary>
	/// <param name="response"></param>
	private void RegisterInstaller(ref string response)
	{
		try
		{
			log.Message("Installation of "+Request["product"]+" on machine "+Request["machineid"]);
		}
		catch (System.Exception ex)
		{
			response = "er:" + ex.GetHashCode() + ":" + ex.Message;
		}
	}

	private void SendEmail(ref string response)
	{
		try
		{
			Milan.IO.IniFile emailListIni = new Milan.IO.IniFile("../App_Data/maillist.txt");
			var emails = emailListIni.IniReadValue("maillist", Request["dest"]).Split(',');
			foreach (var email in emails)
			{
				Mail.Simple(Request["subject"], Request["message"],email);
				log.Message("Email sent to: " + email + " on " + Request["subject"]);
			}
		}
		catch (System.Exception ex)
		{
			response = "er:" + ex.GetHashCode() + ":" + ex.Message;
		}
	}

}
